package com.tnovoselec.android.ui;

import android.content.Context;
import android.support.v4.view.ViewConfigurationCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.ListView;


public class MyListView extends ListView {

    private int mTouchSlop;
    private float mLastMotionX;
    private float mLastMotionY;
    private boolean mIntercept;
    private boolean mXmoved;;
    private boolean mYmoved;

    public MyListView(Context context, AttributeSet attrs, int defStyle) {
	super(context, attrs, defStyle);
	init();
    }

    public MyListView(Context context, AttributeSet attrs) {
	super(context, attrs);
	init();
    }

    public MyListView(Context context) {
	super(context);
	init();
    }

    private void init() {
	mIntercept = false;
	mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(ViewConfiguration.get(getContext()));
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
	final int action = ev.getAction();

	switch (action & MotionEvent.ACTION_MASK) {
	    case MotionEvent.ACTION_DOWN: {
		mLastMotionX = ev.getX();
		mLastMotionY = ev.getY();
		mXmoved = false;
		mYmoved = false;
		mIntercept = false;
		break;
	    }
	    case MotionEvent.ACTION_MOVE: {
		if (mXmoved || mYmoved) {
		    break;
		}
		final int xDiff = (int) Math.abs(ev.getX() - mLastMotionX);
		final int yDiff = (int) Math.abs(ev.getY() - mLastMotionY);

		final int touchSlop = mTouchSlop;
		mXmoved = xDiff > touchSlop;
		mYmoved = yDiff > touchSlop;

		if (mXmoved) {
		    mIntercept = true;
		}
		break;
	    }
	    case MotionEvent.ACTION_CANCEL:
	    case MotionEvent.ACTION_UP:
		mXmoved = false;
		mYmoved = false;
		mIntercept = false;
		break;
	}
	if (mIntercept) {
	    return false;
	} else {
	    return super.onInterceptTouchEvent(ev);
	}
    }

}
